package org.javaboy.vhr.bim.utils;

import com.banboocloud.Codec.BamboocloudFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.core.ReflectUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;


public abstract class BamboocloudUtils {
	private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);
	public static boolean checkUsernamePassword(String username, String password) {
			logger.info("username --->" + username + "  password --- >" + password + " ----ok");
		if("bbcadmin".equals(username)&&"P@sswOrd".equals(password)) {
			return true;
		}
		else {
			return false;
		}
	}

	public static String getPlaintext(String ciphertext, String key, String type) {
		return BamboocloudFacade.decrypt(ciphertext, key, type);
	}

	public static void main(String[] args) {
		String aes = BamboocloudUtils.getPlaintext("3DJTcARkymQQtbxs3jb1i4F3bIEPpNXun3dEJGLJKlsy+Wx/Q3oKK9fT3n2QJO1yQopVkG7Y58bDjLXfxwwMPFRC4wa0Gu3+9UOfuBI0YxcHzx+D2M9d60rONgZChi29JkZbxTcNpWVNXFu1zZzhsOOpEN6o9p62wS33fpMev6kjVgs9jaBfYH3Uj2JNZ2ESDrcUs9Yl9dj6Wdn948FAIw==", "123456", "AES");
		System.out.println(aes);
	}

	public static Boolean verify(Map<String, Object> reqmap, String type) {
		Map<String, Object> verifymap = new TreeMap<String, Object>();
		StringBuffer sb = new StringBuffer();
		Iterator<String> it = reqmap.keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			verifymap.put(key, reqmap.get(key));
		}
		Iterator<String> ittree = verifymap.keySet().iterator();
		while (ittree.hasNext()) {
			String key = (String) ittree.next();
			if (!"signature".equals(key)) {
				sb.append(key).append("=").append(verifymap.get(key)).append("&");
			}
		}
		sb.deleteCharAt(sb.length() - 1);
		System.out.println(reqmap.get("signature") + "  now  " + sb.toString());
		return BamboocloudFacade.verify(reqmap.get("signature").toString(), sb.toString(), type);
	}

	public static String getRequestBody(HttpServletRequest request) {
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		String str = "";
		try {
			br = request.getReader();
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
			if (br != null)
				try {
					br.close();
				} catch (IOException eo) {
					eo.printStackTrace();
				}
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}

}